<template>
  <div
    class="subsidy-overview-dashboard"
    role="main"
    aria-label="项目补助概况看板"
  >
    <!-- 顶部筛选区 -->
    <div class="filter-bar">
      <div class="filter-left">
        <span class="filter-label">选择时间</span>
        <input
          type="date"
          class="date-input"
          v-model="dateRange[0]"
          @change="onDateChange"
        />
        <span>~</span>
        <input
          type="date"
          class="date-input"
          v-model="dateRange[1]"
          @change="onDateChange"
        />
      </div>
      <div class="filter-right">
        <button
          v-for="(btn, idx) in timeButtons"
          :key="btn.label"
          class="filter-btn"
          :class="{ active: selectedTimeBtn === idx }"
          @click="onTimeBtnClick(idx)"
        >
          {{ btn.label }}
        </button>
        <!-- 新增：数据导出按钮 -->
        <button class="export-btn" @click="exportData" :disabled="loading">
          📊 导出数据
        </button>
      </div>
    </div>

    <div class="section-title">实时数据统计</div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card yellow">
        <div class="icon"><span>💰</span></div>
        <div class="info">
          <div class="value">{{ formatNumber(stats.totalSubsidy) }}</div>
          <div class="unit">万元</div>
          <div class="label">总补助金额</div>
        </div>
      </div>
      <div class="stat-card blue">
        <div class="icon"><span>📋</span></div>
        <div class="info">
          <div class="value">{{ formatNumber(stats.projectCount) }}</div>
          <div class="unit">个</div>
          <div class="label">补助项目数</div>
        </div>
      </div>
      <div class="stat-card orange">
        <div class="icon"><span>🏆</span></div>
        <div class="info">
          <div class="value">{{ stats.maxProject }}</div>
          <div class="unit"></div>
          <div class="label">最大补助项目</div>
        </div>
      </div>
      <div class="stat-card green">
        <div class="icon"><span>📈</span></div>
        <div class="info">
          <div class="value">{{ stats.avgSubsidy }}%</div>
          <div class="unit"></div>
          <div class="label">平均补助率</div>
        </div>
      </div>
    </div>

    <div class="divider"></div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <p>数据加载中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-if="error" class="error-message" role="alert">
      <div class="error-icon">⚠️</div>
      <h3>数据加载失败</h3>
      <p>{{ error }}</p>
      <button @click="retryLoad" class="retry-btn">重试</button>
    </div>

    <div class="charts-section" v-show="!loading && !error">
      <!-- 左侧：趋势图及筛选 -->
      <div class="chart-block">
        <div class="chart-header">
          <span class="chart-title">补助金额趋势图</span>
          <div class="chart-filters">
            <select v-model="selectedProvince" @change="onProvinceChange">
              <option value="">请选择省份</option>
              <option v-for="p in provinceList" :key="p" :value="p">
                {{ p }}
              </option>
            </select>
            <select
              v-model="selectedCity"
              :disabled="!selectedProvince"
              @change="onCityChange"
            >
              <option value="">请选择城市</option>
              <option v-for="c in cityList" :key="c" :value="c">{{ c }}</option>
            </select>
          </div>
        </div>
        <div class="chart-content">
          <div class="y-axis-label">补助金额/万元</div>
          <div ref="trendChartRef" class="chart-echarts trend"></div>
        </div>
      </div>

      <!-- 右侧：类型分布图及筛选 -->
      <div class="chart-block">
        <div class="chart-header">
          <span class="chart-title">补助类型分布图</span>
          <div class="chart-filters">
            <select v-model="selectedType" @change="onTypeChange">
              <option value="">请选择类型</option>
              <option v-for="t in typeList" :key="t" :value="t">{{ t }}</option>
            </select>
          </div>
        </div>
        <div class="chart-content">
          <div ref="typeChartRef" class="chart-echarts type"></div>
          <div class="legend-block">
            <div class="legend-title">图例</div>
            <ul class="legend-list">
              <li class="legend-item" v-for="item in typeData" :key="item.name">
                <span
                  class="legend-color"
                  :style="{ background: item.itemStyle.color }"
                ></span>
                {{ item.name }}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <!-- 性能监控面板 -->
    <div class="performance-panel" v-if="showPerformance">
      <h3>性能监控</h3>
      <div class="performance-metrics">
        <div class="metric">
          <span class="metric-label">数据加载时间:</span>
          <span class="metric-value">{{ performance.loadTime }}ms</span>
        </div>
        <div class="metric">
          <span class="metric-label">图表渲染时间:</span>
          <span class="metric-value">{{ performance.renderTime }}ms</span>
        </div>
        <div class="metric">
          <span class="metric-label">内存使用:</span>
          <span class="metric-value">{{ performance.memory }}MB</span>
        </div>
      </div>
    </div>

    <!-- 键盘导航提示 -->
    <div class="keyboard-hint" role="note" aria-live="polite">
      <p>
        💡 提示：使用 Tab 键在筛选器间导航，按 E 键导出数据，按 P 键显示性能监控
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  watch,
  onMounted,
  onBeforeUnmount,
  computed,
  nextTick,
} from "vue";
import * as echarts from "echarts";

// 类型定义
interface TimeButton {
  label: string;
  range: [string, string];
}

interface Stats {
  totalSubsidy: number;
  projectCount: number;
  maxProject: string;
  avgSubsidy: number;
}

interface TypeDataItem {
  value: number;
  name: string;
  itemStyle: { color: string };
}

interface ChartData {
  stats: Stats;
  trend: number[];
  type: TypeDataItem[];
}

interface StaticData {
  [province: string]: {
    [city: string]: {
      [timeLabel: string]: ChartData;
    };
  };
}

interface Performance {
  loadTime: number;
  renderTime: number;
  memory: number;
}

// 常量定义
const TIME_BUTTONS: TimeButton[] = [
  { label: "近30天", range: ["2024-05-01", "2024-05-30"] },
  { label: "近7天", range: ["2024-05-24", "2024-05-30"] },
  { label: "上周", range: ["2024-05-20", "2024-05-26"] },
  { label: "上月", range: ["2024-04-01", "2024-04-30"] },
];

const PROVINCE_LIST = ["江苏省", "浙江省", "山东省"] as const;
const CITY_MAP: Record<string, string[]> = {
  江苏省: ["南京市", "苏州市"],
  浙江省: ["杭州市", "宁波市"],
  山东省: ["济南市", "青岛市"],
};
const TYPE_LIST = ["种植补助", "设备补助", "技术补助", "基础设施补助"] as const;
const TREND_YEARS = [
  "2012年",
  "2013年",
  "2014年",
  "2015年",
  "2016年",
  "2017年",
  "2018年",
  "2019年",
];

// 响应式数据
const selectedTimeBtn = ref(0);
const dateRange = ref<[string, string]>([
  TIME_BUTTONS[0].range[0],
  TIME_BUTTONS[0].range[1],
]);
const selectedProvince = ref("");
const cityList = ref<string[]>([]);
const selectedCity = ref("");
const selectedType = ref("");

// 状态管理
const loading = ref(false);
const error = ref<string | null>(null);
const showPerformance = ref(false);

const stats = reactive<Stats>({
  totalSubsidy: 0,
  projectCount: 0,
  maxProject: "-",
  avgSubsidy: 0,
});

const trendData = ref<number[]>([]);
const typeData = ref<TypeDataItem[]>([]);

// 性能监控
const performance = reactive<Performance>({
  loadTime: 0,
  renderTime: 0,
  memory: 0,
});

// ECharts refs
const trendChartRef = ref<HTMLDivElement | null>(null);
const typeChartRef = ref<HTMLDivElement | null>(null);
let trendChart: echarts.ECharts | null = null;
let typeChart: echarts.ECharts | null = null;

// 计算属性
const timeButtons = computed(() => TIME_BUTTONS);
const provinceList = computed(() => PROVINCE_LIST);
const typeList = computed(() => TYPE_LIST);

// 缓存机制
const dataCache = new Map<string, ChartData>();
const chartCache = new Map<string, echarts.ECharts>();

// 优化后的多维静态数据源
const staticData: StaticData = {
  江苏省: {
    南京市: {
      近30天: {
        stats: {
          totalSubsidy: 15_000,
          projectCount: 45,
          maxProject: "智能种植项目",
          avgSubsidy: 85,
        },
        trend: [1200, 1350, 1280, 1400, 1500, 1600, 1580, 1550],
        type: [
          { value: 6000, name: "种植补助", itemStyle: { color: "#f5222d" } },
          { value: 4500, name: "设备补助", itemStyle: { color: "#1890ff" } },
          { value: 3000, name: "技术补助", itemStyle: { color: "#52c41a" } },
          {
            value: 1500,
            name: "基础设施补助",
            itemStyle: { color: "#faad14" },
          },
        ],
      },
      近7天: {
        stats: {
          totalSubsidy: 12_000,
          projectCount: 38,
          maxProject: "智能种植项目",
          avgSubsidy: 82,
        },
        trend: [1000, 1100, 1150, 1200, 1300, 1350, 1380, 1400],
        type: [
          { value: 5000, name: "种植补助", itemStyle: { color: "#f5222d" } },
          { value: 3500, name: "设备补助", itemStyle: { color: "#1890ff" } },
          { value: 2500, name: "技术补助", itemStyle: { color: "#52c41a" } },
          {
            value: 1000,
            name: "基础设施补助",
            itemStyle: { color: "#faad14" },
          },
        ],
      },
    },
    苏州市: {
      近30天: {
        stats: {
          totalSubsidy: 12_000,
          projectCount: 35,
          maxProject: "绿色农业项目",
          avgSubsidy: 78,
        },
        trend: [1000, 1100, 1050, 1200, 1300, 1250, 1280, 1250],
        type: [
          { value: 4800, name: "种植补助", itemStyle: { color: "#f5222d" } },
          { value: 3600, name: "设备补助", itemStyle: { color: "#1890ff" } },
          { value: 2400, name: "技术补助", itemStyle: { color: "#52c41a" } },
          {
            value: 1200,
            name: "基础设施补助",
            itemStyle: { color: "#faad14" },
          },
        ],
      },
      近7天: {
        stats: {
          totalSubsidy: 10_000,
          projectCount: 32,
          maxProject: "绿色农业项目",
          avgSubsidy: 75,
        },
        trend: [800, 900, 950, 1000, 1100, 1150, 1180, 1200],
        type: [
          { value: 4000, name: "种植补助", itemStyle: { color: "#f5222d" } },
          { value: 3000, name: "设备补助", itemStyle: { color: "#1890ff" } },
          { value: 2000, name: "技术补助", itemStyle: { color: "#52c41a" } },
          {
            value: 1000,
            name: "基础设施补助",
            itemStyle: { color: "#faad14" },
          },
        ],
      },
    },
  },
  浙江省: {
    杭州市: {
      近30天: {
        stats: {
          totalSubsidy: 18_000,
          projectCount: 52,
          maxProject: "智慧农业项目",
          avgSubsidy: 88,
        },
        trend: [1500, 1600, 1700, 1800, 1900, 2000, 2100, 2200],
        type: [
          { value: 7200, name: "种植补助", itemStyle: { color: "#f5222d" } },
          { value: 5400, name: "设备补助", itemStyle: { color: "#1890ff" } },
          { value: 3600, name: "技术补助", itemStyle: { color: "#52c41a" } },
          {
            value: 1800,
            name: "基础设施补助",
            itemStyle: { color: "#faad14" },
          },
        ],
      },
      近7天: {
        stats: {
          totalSubsidy: 15_000,
          projectCount: 45,
          maxProject: "智慧农业项目",
          avgSubsidy: 85,
        },
        trend: [1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900],
        type: [
          { value: 6000, name: "种植补助", itemStyle: { color: "#f5222d" } },
          { value: 4500, name: "设备补助", itemStyle: { color: "#1890ff" } },
          { value: 3000, name: "技术补助", itemStyle: { color: "#52c41a" } },
          {
            value: 1500,
            name: "基础设施补助",
            itemStyle: { color: "#faad14" },
          },
        ],
      },
    },
  },
};

// 优化的数据查找函数
const findData = (
  province: string,
  city: string,
  timeLabel: string
): ChartData => {
  const cacheKey = `${province}-${city}-${timeLabel}`;

  if (dataCache.has(cacheKey)) {
    return dataCache.get(cacheKey)!;
  }

  const data = staticData[province]?.[city]?.[timeLabel] ||
    staticData[province]?.[city]?.["近30天"] ||
    staticData[province]?.[Object.keys(staticData[province] || {})[0]]?.[
      "近30天"
    ] || {
      stats: {
        totalSubsidy: 0,
        projectCount: 0,
        maxProject: "-",
        avgSubsidy: 0,
      },
      trend: [],
      type: [],
    };

  dataCache.set(cacheKey, data);
  return data;
};

// 兼容的 performance.now 函数
const getCurrentTime = () => {
  if (
    typeof window !== "undefined" &&
    window.performance &&
    window.performance.now
  ) {
    return window.performance.now();
  }
  return Date.now();
};

// 优化的图表渲染函数
const renderTrend = async () => {
  if (!trendChartRef.value) return;

  try {
    const startTime = getCurrentTime();

    if (!trendChart) {
      trendChart = echarts.init(trendChartRef.value);
      chartCache.set("trend", trendChart);
    }

    const option = {
      tooltip: {
        trigger: "axis",
        axisPointer: { type: "cross" },
      },
      grid: {
        left: "10%",
        right: "10%",
        bottom: "15%",
        top: "15%",
      },
      xAxis: {
        type: "category",
        data: TREND_YEARS,
        axisLine: { lineStyle: { color: "#e0e0e0" } },
        axisLabel: { color: "#888" },
        axisTick: { show: false },
      },
      yAxis: {
        type: "value",
        name: "补助金额/万元",
        axisLine: { lineStyle: { color: "#e0e0e0" } },
        axisLabel: { color: "#888" },
        splitLine: { lineStyle: { color: "#f0f0f0" } },
        axisTick: { show: false },
      },
      series: [
        {
          name: "补助金额",
          type: "line",
          data: trendData.value,
          smooth: true,
          lineStyle: { color: "#1890ff", width: 3 },
          itemStyle: { color: "#1890ff" },
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: "rgba(24,144,255,0.3)" },
                { offset: 1, color: "rgba(24,144,255,0.05)" },
              ],
            },
          },
          symbol: "circle",
          symbolSize: 6,
        },
      ],
    };

    trendChart.setOption(option, true);

    performance.renderTime = Math.round(getCurrentTime() - startTime);
  } catch (error) {
    console.error("渲染趋势图失败:", error);
    throw error;
  }
};

const renderType = async () => {
  if (!typeChartRef.value) return;

  try {
    if (!typeChart) {
      typeChart = echarts.init(typeChartRef.value);
      chartCache.set("type", typeChart);
    }

    const option = {
      tooltip: {
        trigger: "item",
        formatter: "{b}: {c}万元 ({d}%)",
      },
      legend: { show: false },
      series: [
        {
          name: "补助类型",
          type: "pie",
          radius: "70%",
          center: ["50%", "50%"],
          label: {
            formatter: "{b}\n{c}万元 ({d}%)",
            fontSize: 14,
            color: "#666",
          },
          data: typeData.value,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    };

    typeChart.setOption(option, true);
  } catch (error) {
    console.error("渲染类型图失败:", error);
    throw error;
  }
};

// 交互逻辑
const onTimeBtnClick = (idx: number) => {
  selectedTimeBtn.value = idx;
  dateRange.value = [...TIME_BUTTONS[idx].range];
  refreshData();
};

const onDateChange = () => {
  selectedTimeBtn.value = -1;
  refreshData();
};

const onProvinceChange = () => {
  cityList.value = selectedProvince.value
    ? CITY_MAP[selectedProvince.value]
    : [];
  selectedCity.value = "";
  refreshData();
};

const onCityChange = () => {
  refreshData();
};

const onTypeChange = () => {
  refreshData();
};

// 数据导出功能
const exportData = () => {
  try {
    const data = {
      stats: stats,
      trend: trendData.value,
      type: typeData.value,
      filters: {
        province: selectedProvince.value,
        city: selectedCity.value,
        type: selectedType.value,
        timeRange: dateRange.value,
      },
      exportTime: new Date().toISOString(),
    };

    const blob = new Blob([JSON.stringify(data, null, 2)], {
      type: "application/json",
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `subsidy-data-${new Date().toISOString().split("T")[0]}.json`;
    a.click();
    URL.revokeObjectURL(url);
  } catch (error) {
    console.error("导出数据失败:", error);
    alert("导出数据失败，请重试");
  }
};

// 重试加载
const retryLoad = () => {
  error.value = null;
  refreshData();
};

// 优化的数据刷新函数
const refreshData = async () => {
  try {
    const startTime = getCurrentTime();
    loading.value = true;
    error.value = null;

    const province = selectedProvince.value || "江苏省";
    const city =
      selectedCity.value ||
      (CITY_MAP[province] ? CITY_MAP[province][0] : "南京市");
    const timeLabel =
      selectedTimeBtn.value >= 0
        ? TIME_BUTTONS[selectedTimeBtn.value].label
        : "近30天";

    const data = findData(province, city, timeLabel);

    Object.assign(stats, data.stats);
    trendData.value = data.trend;
    typeData.value = data.type;

    await nextTick();
    await Promise.all([renderTrend(), renderType()]);

    performance.loadTime = Math.round(getCurrentTime() - startTime);
    performance.memory = Math.round(
      (performance as any).memory?.usedJSHeapSize / 1024 / 1024 || 0
    );
  } catch (err) {
    console.error("数据刷新失败:", err);
    error.value = err instanceof Error ? err.message : "数据加载失败，请重试";
  } finally {
    loading.value = false;
  }
};

// 工具函数
const formatNumber = (n: number) => n.toLocaleString();

// 键盘事件处理
const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === "e" || event.key === "E") {
    event.preventDefault();
    exportData();
  } else if (event.key === "p" || event.key === "P") {
    event.preventDefault();
    showPerformance.value = !showPerformance.value;
  }
};

// 生命周期
onMounted(async () => {
  try {
    cityList.value = [];
    document.addEventListener("keydown", handleKeydown);
    await refreshData();
  } catch (err) {
    console.error("组件初始化失败:", err);
    error.value = "组件初始化失败";
  }
});

// 防抖优化
let refreshTimer: NodeJS.Timeout | null = null;
const debouncedRefresh = () => {
  if (refreshTimer) {
    clearTimeout(refreshTimer);
  }
  refreshTimer = setTimeout(refreshData, 100);
};

watch([selectedProvince, selectedCity, selectedType], debouncedRefresh);

onBeforeUnmount(() => {
  if (refreshTimer) {
    clearTimeout(refreshTimer);
  }

  document.removeEventListener("keydown", handleKeydown);

  chartCache.forEach((chart) => chart?.dispose());
  chartCache.clear();
  dataCache.clear();
});
</script>

<style scoped>
.subsidy-overview-dashboard {
  padding: 36px 36px 56px 36px;
  background: linear-gradient(135deg, #f6f8fb 0%, #f0f4f8 100%);
  min-height: 100vh;
  animation: fadeIn 0.6s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 22px 36px;
  border-radius: 20px;
  margin-bottom: 36px;
  box-shadow: 0 6px 32px 0 rgba(0, 0, 0, 0.06);
}

.filter-label {
  font-weight: 700;
  color: #222;
  margin-right: 12px;
  font-size: 17px;
}

.filter-left {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 16px;
  color: #666;
}

.date-input {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 7px 14px;
  font-size: 16px;
  background: #fafbfc;
  transition: border 0.2s;
}

.date-input:focus {
  border: 1.5px solid #1890ff;
  outline: none;
}

.filter-right {
  display: flex;
  gap: 16px;
}

.filter-btn {
  background: #f2f4f8;
  border: none;
  border-radius: 8px;
  padding: 10px 32px;
  font-size: 16px;
  color: #666;
  cursor: pointer;
  font-weight: 600;
  transition: background 0.2s, color 0.2s;
  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.03);
}

.filter-btn.active,
.filter-btn:hover {
  background: #1890ff;
  color: #fff;
}

.export-btn {
  background: #52c41a;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 10px 24px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.2s;
  box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.03);
}

.export-btn:hover:not(:disabled) {
  background: #73d13d;
}

.export-btn:disabled {
  background: #d9d9d9;
  color: #999;
  cursor: not-allowed;
}

.section-title {
  font-size: 22px;
  font-weight: 800;
  color: #222;
  margin-bottom: 24px;
  margin-top: 10px;
  letter-spacing: 1px;
  position: relative;
}

.section-title::after {
  content: "";
  position: absolute;
  bottom: -8px;
  left: 0;
  width: 40px;
  height: 3px;
  background: linear-gradient(90deg, #1890ff, #52c41a);
  border-radius: 2px;
}

.stats-cards {
  display: flex;
  gap: 36px;
  margin-bottom: 36px;
}

.stat-card {
  flex: 1;
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 20px;
  padding: 36px 40px;
  box-shadow: 0 6px 32px 0 rgba(0, 0, 0, 0.06);
  min-width: 220px;
  position: relative;
  transition: box-shadow 0.2s;
  transform: translateZ(0);
  backface-visibility: hidden;
}

.stat-card:hover {
  transform: translateY(-2px) translateZ(0);
  box-shadow: 0 12px 40px 0 rgba(24, 144, 255, 0.13);
}

.stat-card .icon {
  font-size: 54px;
  margin-right: 26px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 72px;
  height: 72px;
  border-radius: 16px;
  background: #f5f5f5;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
}

.stat-card.yellow .icon {
  background: #fffbe6;
  color: #faad14;
}

.stat-card.blue .icon {
  background: #e6f7ff;
  color: #1890ff;
}

.stat-card.orange .icon {
  background: #fff2e8;
  color: #fa541c;
}

.stat-card.green .icon {
  background: #f6ffed;
  color: #52c41a;
}

.stat-card .info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.stat-card .info .value {
  font-size: 36px;
  font-weight: bold;
  color: #faad14;
  line-height: 1.1;
  letter-spacing: 1px;
  animation: dataLoad 0.5s ease-out;
}

.stat-card.blue .info .value {
  color: #1890ff;
}

.stat-card.orange .info .value {
  color: #fa541c;
}

.stat-card.green .info .value {
  color: #52c41a;
}

.stat-card .info .unit {
  font-size: 16px;
  color: #888;
  margin-bottom: 2px;
  margin-top: 2px;
}

.stat-card .info .label {
  font-size: 17px;
  color: #888;
  margin-top: 8px;
  font-weight: 500;
}

@keyframes dataLoad {
  0% {
    opacity: 0;
    transform: scale(0.95);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

.divider {
  height: 24px;
  background: transparent;
}

/* 加载状态样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loading-overlay p {
  font-size: 16px;
  color: #666;
  font-weight: 500;
}

/* 错误状态样式 */
.error-message {
  background: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 12px;
  padding: 24px;
  margin: 20px 0;
  text-align: center;
  box-shadow: 0 4px 12px rgba(255, 77, 79, 0.1);
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.error-message h3 {
  color: #cf1322;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
}

.error-message p {
  color: #666;
  margin-bottom: 16px;
  line-height: 1.5;
}

.retry-btn {
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 10px 24px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;
}

.retry-btn:hover {
  background: #40a9ff;
}

.charts-section {
  display: flex;
  gap: 36px;
  animation: slideUp 0.8s ease-out 0.2s both;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.chart-block {
  flex: 1;
  background: #fff;
  border-radius: 20px;
  padding: 36px 36px 44px 36px;
  box-shadow: 0 6px 32px 0 rgba(0, 0, 0, 0.06);
  display: flex;
  flex-direction: column;
  min-width: 0;
  position: relative;
  overflow: hidden;
}

.chart-block::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #1890ff, #52c41a, #faad14);
  opacity: 0;
  transition: opacity 0.3s;
}

.chart-block:hover::before {
  opacity: 1;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 22px;
}

.chart-title {
  font-size: 20px;
  font-weight: 700;
  color: #222;
}

.chart-filters {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.chart-filters select {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 8px 22px;
  font-size: 16px;
  color: #666;
  background: #fafbfc;
  transition: border 0.2s;
  cursor: pointer;
  user-select: none;
  min-width: 120px;
}

.chart-filters select:focus {
  border: 1.5px solid #1890ff;
  outline: none;
  box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
}

.chart-filters select:hover {
  border-color: #1890ff;
  background: #f0f8ff;
}

.chart-filters select:disabled {
  background: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
}

.chart-content {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 36px;
  width: 100%;
  min-height: 340px;
}

.chart-echarts {
  width: 360px;
  height: 300px;
  min-width: 240px;
  min-height: 200px;
  background: #f7f8fa;
  border-radius: 16px;
  margin-top: 8px;
  position: relative;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
  will-change: transform;
  transform: translateZ(0);
  transition: opacity 0.3s ease;
}

.chart-echarts.updating {
  opacity: 0.7;
}

.y-axis-label {
  position: absolute;
  left: -60px;
  top: 50px;
  font-size: 15px;
  color: #888;
  transform: rotate(-90deg);
  transform-origin: left bottom;
}

.legend-block {
  flex: 1;
  margin-left: 24px;
  margin-top: 32px;
}

.legend-title {
  font-size: 16px;
  color: #888;
  margin-bottom: 12px;
  font-weight: 600;
}

.legend-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #666;
  margin-bottom: 10px;
  font-weight: 500;
}

.legend-color {
  display: inline-block;
  width: 18px;
  height: 18px;
  border-radius: 5px;
  margin-right: 12px;
}

/* 性能监控面板 */
.performance-panel {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-top: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e8e8e8;
}

.performance-panel h3 {
  color: #333;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
}

.performance-metrics {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
}

.metric {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.metric-label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.metric-value {
  font-size: 16px;
  color: #1890ff;
  font-weight: 600;
}

/* 键盘导航提示 */
.keyboard-hint {
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 8px;
  padding: 12px 16px;
  margin-top: 20px;
  text-align: center;
}

.keyboard-hint p {
  color: #1890ff;
  font-size: 14px;
  margin: 0;
  font-weight: 500;
}

/* 响应式优化 */
@media (max-width: 1400px) {
  .subsidy-overview-dashboard {
    padding: 28px 28px 48px 28px;
  }

  .charts-section {
    gap: 28px;
  }
}

@media (max-width: 1200px) {
  .charts-section {
    flex-direction: column;
    gap: 28px;
  }

  .stats-cards {
    flex-direction: column;
    gap: 28px;
  }

  .chart-content {
    flex-direction: column;
    gap: 16px;
  }

  .legend-block {
    margin-left: 0;
    margin-top: 16px;
  }
}

@media (max-width: 768px) {
  .subsidy-overview-dashboard {
    padding: 20px 20px 40px 20px;
  }

  .section-title {
    font-size: 20px;
    margin-bottom: 20px;
  }

  .charts-section {
    gap: 20px;
  }

  .chart-filters {
    flex-direction: column;
    align-items: stretch;
  }

  .chart-filters select {
    min-width: auto;
  }

  .filter-bar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .filter-right {
    justify-content: center;
  }

  .performance-metrics {
    flex-direction: column;
    gap: 12px;
  }
}

/* 高对比度模式支持 */
@media (prefers-contrast: high) {
  .chart-filters select {
    border-width: 2px;
  }

  .stat-card {
    border: 2px solid #333;
  }

  .chart-block {
    border: 2px solid #333;
  }
}

/* 减少动画模式支持 */
@media (prefers-reduced-motion: reduce) {
  .subsidy-overview-dashboard,
  .charts-section,
  .stat-card .info .value {
    animation: none;
  }

  .loading-spinner {
    animation: none;
  }
}
</style> 